package jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

public class RegDemo {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // 提示用户输入信息
        System.out.print("请输入用户名: ");
        String username = scanner.nextLine();
        System.out.print("请输入密码: ");
        String password = scanner.nextLine();
        System.out.print("请输入昵称: ");
        String nickname = scanner.nextLine();
        System.out.print("请输入年龄: ");
        int age = scanner.nextInt();

        // 使用DBUtil获取数据库连接
        try (Connection connection = DBUtil.getConnection()) {
            // 创建SQL插入语句
            String sql = "INSERT INTO user(username, password, nickname, age) VALUES (?, ?, ?, ?)";
            try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
                preparedStatement.setString(1, username);
                preparedStatement.setString(2, password);
                preparedStatement.setString(3, nickname);
                preparedStatement.setInt(4, age);

                // 执行SQL插入语句
                int num = preparedStatement.executeUpdate();
                if (num > 0) {
                    System.out.println("注册成功！");
                } else {
                    System.out.println("注册失败！");
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            scanner.close();
        }
    }
}
